//
//  VideoDetailViewController.m
//  qiuShiJiangHu
//
//  Created by xalo on 16/1/26.
//  Copyright © 2016年 糗事江湖项目组. All rights reserved.
//

#import "VideoDetailViewController.h"
#import "VideoCell.h"
#import "HttpHelperWithVideo.h"
#import "VideoModel.h"
#import "CommentCell.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "CommentModel.h"
@interface VideoDetailViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) AVPlayerViewController *moviePlayer;

@property (nonatomic,strong) NSMutableArray *modelArray;

@property (nonatomic,strong) UITextField *TF;

@property (nonatomic,strong) UITextField *tt;

@end

@implementation VideoDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tabBarController.tabBar.hidden = YES;
//注册nib
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoCell" bundle:nil] forCellReuseIdentifier:@"videoCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CommentCell" bundle:nil] forCellReuseIdentifier:@"commentCell"];
    
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    
    [self setData];
    
    [self makeTextFieldWithView];
    
}
//请求评论数据
-(void)setData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"http://m2.qiushibaike.com/article/%ld/comments",self.ID]];
        NSURLSession *session=[NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask=[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSDictionary *rootDic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSArray *array=rootDic[@"items"];
            self.modelArray=[NSMutableArray array];
            for (NSDictionary *dic in array) {
                CommentModel *model=[[CommentModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.modelArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [MBProgressHUD hideHUDForView:self.view  animated:YES];
            });
        }];
        [dataTask resume];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.modelArray.count+1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row==0) {
        VideoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"videoCell" forIndexPath:indexPath];
        
        cell.commentButton.hidden = YES;
        
      VideoModel *model=[[HttpHelperWithVideo sharedManager] returnModelWithIndex:self.index];
        [cell setContentViewWithModel:model];
        
        [cell.playButton addTarget:self action:@selector(playVideo) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.moviePlayer removeFromParentViewController];

        return cell;
    }
    
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
    CommentModel *model=self.modelArray[indexPath.row-1];
    [cell setContentWithModel:model];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        NSString *str=[[HttpHelperWithVideo sharedManager] returnModelWithIndex:self.index].content;
        CGRect bound = [str boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-10, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17.0] forKey:NSFontAttributeName] context:nil];
        
        return 530 + bound.size.height;
    }else{
        CommentModel *model=self.modelArray[indexPath.row-1];
        NSString *str=model.content;
        CGRect bound = [str boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-10, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17.0] forKey:NSFontAttributeName] context:nil];
        
        return 80+bound.size.height;
    }
}

-(void)playVideo
{
    VideoModel *model = [[HttpHelperWithVideo sharedManager] returnModelWithIndex:self.index];
    
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:model.high_url]];
    
    self.moviePlayer = [[AVPlayerViewController alloc] init];
    
    self.moviePlayer.player = [AVPlayer playerWithPlayerItem:item];

    self.moviePlayer.view.frame = CGRectMake(10, 80, 355, 355);
    
    [self.view addSubview:_moviePlayer.view];
    
    [self.moviePlayer.player play];    

}


-(void)makeTextFieldWithView
{
    self.TF = [[UITextField alloc] initWithFrame:CGRectMake(5, [UIScreen mainScreen].bounds.size.height - 40, [UIScreen mainScreen].bounds.size.width - 10, 40)];
    
    self.TF.placeholder = @"请输入发表内容";
    self.TF.delegate = self;
    
    self.TF.backgroundColor = [UIColor whiteColor];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.TF];
    
    _tt = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 300, 40)];
    
    _tt.backgroundColor = [UIColor whiteColor];
    
    _tt.placeholder = @"请输入发表内容";
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"笑脸"]];
    
    _tt.leftView = imageView;
    
    _tt.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"发送"]];
    imageView1.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    
    [imageView1 addGestureRecognizer:tap];
    
    _tt.rightView = imageView1;
    
    _tt.rightViewMode = UITextFieldViewModeAlways;
    
    _tt.delegate = self;
    
    self.TF.inputAccessoryView = _tt;
}


-(void)tap
{
    NSString *str = self.tt.text;
    
    NSLog(@"%@",str);
    
    self.tt.text = nil;
    
    [self.tt removeFromSuperview];
    
   [self.TF resignFirstResponder];

}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self.tt removeFromSuperview];
    
    [self.TF removeFromSuperview];
}















/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
